package com.springboot.example.monitor.util;

import com.springboot.example.monitor.domain.model.ProjectInfo;
import org.apache.commons.io.IOUtils;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.*;

/**
 * 作者: guo yao
 * 日期: 2016年02月25日
 * 时间: 下午19:06
 */
public class XmlUtil {

//    http://blog.csdn.net/redarmy_chen/article/details/12969219


    /**
     * 读取项目资源
     */
    public static List<ProjectInfo> readServerInfo() throws Throwable {
        String url = XmlUtil.class.getClassLoader().getResource("alert/alert-server.xml").getPath();
        File myXML = new File(url);
        SAXReader reader = new SAXReader();
        Document document = reader.read(myXML);
        Element root = document.getRootElement();
        List<Element> projects = root.elements("project");
        List<ProjectInfo> list = new ArrayList<ProjectInfo>();
        for (Element element : projects) {
            ProjectInfo projectInfo = new ProjectInfo();
            projectInfo.setIp(element.elementText("ip"));
            projectInfo.setPort(element.elementText("port"));
            projectInfo.setName(element.elementText("name"));
            projectInfo.setDomain(element.attribute("domain").getText());
            projectInfo.setNumber(Integer.valueOf(element.attribute("number").getText()));
            projectInfo.setInterval(Integer.valueOf(element.attribute("interval").getText()));
            list.add(projectInfo);
        }
        return list;
    }

    /**
     * 读取发送者信息
     *
     * @return
     * @throws Throwable
     */
    public static Map<String, Boolean> readSenderInfo() throws Throwable {
        String url = XmlUtil.class.getClassLoader().getResource("alert/alert-user.xml").getPath();
        File myXML = new File(url);
        SAXReader reader = new SAXReader();
        Document document = reader.read(myXML);
        Element root = document.getRootElement();
        List<Element> receivers = root.elements("receiver");
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        for (Element element : receivers) {
            String userId = element.elementText("weixin");
            String enable = element.attribute("enable").getText();
            map.put(userId, Boolean.valueOf(enable));
        }
        return map;
    }

    /**
     * 增加logs日志到xml
     *
     * @param info
     * @throws Throwable
     */
    public static void addLogsInfo(ProjectInfo info) throws Throwable {
        String url = XmlUtil.class.getClassLoader().getResource("alert/alert-logs.xml").getPath();
        File myXML = new File(url);
        SAXReader reader = new SAXReader();
        Document document = reader.read(myXML);
        Element root = document.getRootElement();
        Element project = root.addElement("project");
        project.addAttribute("enable", "true");
        project.addAttribute("number", "1");
        Element ip = project.addElement("ip");
        ip.setText(info.getIp());
        Element port = project.addElement("port");
        port.setText(info.getPort());
        Element date = project.addElement("date");
        date.setText(DateHelper.format(new Date(), DateHelper.BOTH));
        Element time = project.addElement("time");
        time.setText(String.valueOf(new Date().getTime()));

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        FileWriter newFile = new FileWriter(new File(url));
        XMLWriter newWriter = new XMLWriter(newFile, format);
        newWriter.write(document);
        newWriter.close();
    }


    public static void main(String[] args) throws Throwable {
        /*String url = XmlUtil.class.getClassLoader().getResource("alert/alert-user.xml").getPath();
        System.out.println(url);
        File myXML = new File(url);
        SAXReader reader = new SAXReader();
        Document document = reader.read(myXML);
        Element root = document.getRootElement();
        XmlUtil.listNodes(root);*/
//        List<ProjectInfo> list = XmlUtil.readServerInfo();
        /*for (ProjectInfo info : list) {
            System.out.println("id=" + info.getIp());
            System.out.println("domain=" + info.getDomain());
        }*/
//        Map<String, Boolean> map = readSenderInfo();
//        System.out.println("==================");
        XmlUtil.updateXml();
    }

    public static void readXml() throws Throwable {
        String text = "<csdn></csdn>";
        Document document = DocumentHelper.parseText(text);

    }

    public static void createXml() {

    }

    public static void updateXml() throws Throwable {
        String url = XmlUtil.class.getClassLoader().getResource("alert/alert-logs.xml").getPath();
        File myXML = new File(url);
        SAXReader reader = new SAXReader();
        Document document = reader.read(myXML);
        Element root = document.getRootElement();
//        List<Element> projects = root.elements("project");
        List<Element> projects = root.selectNodes("/alert-logs/project");
        for (Element element : projects) {
            System.out.println("==" + element.elementText("port"));
            System.out.println("==" + element.attribute("enable").getValue());
            if (element.attribute("enable").getValue().equals("true")) {
//                element.attribute("enable").setValue("false"); // 修改属性
            }
            System.out.println("==d" + element.getText());
//            element.element("port").setText("123"); // 修改内容
//            element.addElement("guoy").setText("cershi");
        }

        // 生成新节点
        root.addComment("增加新节点");
        Element project = root.addElement("project");
        project.addAttribute("enable", "true");
        project.addAttribute("number","3");
        Element ip = project.addElement("id");
        ip.setText("dasdsa");
        Element date = project.addElement("date");
        date.setText(DateHelper.format(new Date(), DateHelper.BOTH));
        Element time = project.addElement("time");
        time.setText(String.valueOf(new Date().getTime()));
        /*List<Element> logs = root.selectNodes("/alert-logs");
        for(Element element : logs){
            Element newproject = element.addElement("project");
            newproject.addAttribute("enable","true");
            newproject.addAttribute("number","1");
//            newproject.element("ip").setText("dsdsd");
        }*/
        // 生成单节点

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        FileWriter newFile = new FileWriter(new File(url));
        XMLWriter newWriter = new XMLWriter(newFile, format);
//        XMLWriter readerWriter = new XMLWriter(System.out, format);
        newWriter.write(document);
        newWriter.close();

//        if (project.isEmpty()) {
        /*Element new_cdata = root.addElement("project");//添加一个元素
        new_cdata.addCDATA("id");
        Element new_ele = root.addElement("project");//添加一个元素
        new_ele.addText("tsdfa");
        Element obj = (Element) root.selectObject("//pro[@type='att']");//根据XPath查找元素
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(System.out, format);
        writer.write(root);
        writer.close();*/

//        }else{
//        }
    }


    //遍历当前节点下的所有节点
    public static void listNodes(Element node) {
        List<Element> receivers = node.elements("receiver");
        for (Element element : receivers) {
            System.out.println("===" + element.getName());
            System.out.println("===" + element.attribute("enable").getName() + "==" + element.attribute("enable").getText());
            System.out.println("===" + element.elementText("weixin"));
        }
//        Element receivers = node.element("receiver");

        /*System.out.println("当前节点的名称：" + node.getName());
        //首先获取当前节点的所有属性节点
        List<Attribute> list = node.attributes();
        //遍历属性节点
        for (Attribute attribute : list) {
            System.out.println("属性" + attribute.getName() + ":" + attribute.getValue());
        }
        //如果当前节点内容不为空，则输出
        if (!(node.getTextTrim().equals(""))) {
            System.out.println(node.getName() + "：" + node.getText());
            //同时迭代当前节点下面的所有子节点
            //使用递归
            Iterator<Element> iterator = node.elementIterator();
            while (iterator.hasNext()) {
                Element e = iterator.next();
            }
        }*/

    }
}